var $=KISSY.all; 
var usernick;
var lastscoreid;
var lastrange;
var lotts;
// KISSY.use("node",function(S,Node){
// var $=Node.all; 
var top_sign = $(".sign").val();
var sid = $(".sid").val();
var top_parameters = $(".top_parameters").val();
function rnd(min, max)
{
	return parseInt((Math.random()*999)%(max-min+1))+min;
}
$(".js-paihang").on("click",function(){
	KISSY.io({
		url: "/?a=tsm_st&m=Shopmodule",
		data:{"top_sign":top_sign},
		success: function(data, textStatus) {
			if(data.status==true){
				game_start();
			}else{
				alert('游戏开始失败！请确认您是在店铺中玩游戏，我们不接待来路不明的客户！');
			}
		},
		error: function(){
			alert('error');
		},
		//发送请求类型是jsonp
		dataType:"jsonp"
	});
	
});
$(".restart").on("click",function(){
	$(".game_over").hide();
	$(".game_restart").hide();
	oStart.fire("click");
});
$(".contend").on("click",function(){
	location.href("/?m=Shopmodule&shop_id="+sid+"&top_parameters="+top_parameters+"&top_sign="+top_sign+"&seller_nick="+$(".seller_nick").val());
});





// TOP.ui("login-btn", {
	// container:".top-login-btn-container",
	// type:"1,1",
	// callback:{
		// login:function(user){alert(user);usernick=user},
		// logout:function(){}
	// }
// });
	var oBg=$('.bg');
	var oMan=$('.man');
	var oScore=$('.score');
	var oGameOver=$('.game_over');
	var oStart=$('.start');
	var oImgLog=$('.img_logo');
	var oProgress=$('.progress');
	var oProgressSpan=$('span');
	var oShadow=$('.shadow');
	var oPopup=$('.popup');
	var oCommitBtn=$('.commit_btn');
	var oCloseBtn=$('.clos');
	var iTimerBullet=null;
	var aBullet=[];
	var MAX_SPEED=5;
	var MIN_SPEED=2;
	var SCREEN_TIME=3;
	var COUNT_BULLET=10;
	var iLevel=1;
	var iScore=0;
	var i=0;
	
	
				
	oCommitBtn.on("click",function ()
	{
		// 获取游戏排行榜
		KISSY.io({
			url: "/?a=getrange&m=Shopmodule&c=user",
			data:{"curtool":$(".curtool").val(),"sid":$(".sid").val()},
			success: function(data, textStatus) {
				if(data.data){
					var msg="本轮最好成绩：坚持"+data.data[0].score+"秒，前10名成绩：<br />";
					for(var i=0;i<data.data.length;i++){
						msg+="网友："+data.data[i].usernick+"，坚持："+data.data[i].score+"秒，获得第"+data.data[i].range_level+"名，抽奖："+data.data[i].lotts+"次<br />";
					}
					if(data.data.length<10){msg+="这一轮还不到10人玩游戏，加油拿名次呀！";}
				}else{
					var msg = "这一轮还没有人玩哦！赶紧抢占第一名！";
				}
				gameDialog("排行榜",msg,"event",false,false,10);
			},
			error: function(){
				alert('error');
			},
			//发送请求类型是jsonp
			dataType:"jsonp"
		});
		// var oScore=$('.cmt_score');
		// var oLevel=$('.cmt_level');
		// var oName=$('.cmt_name');
		
		// oShadow.show();
		// oPopup.show();
		
		// oScore.val(iScore);
		// oLevel.val(iLevel);
	});
	
	oCloseBtn.on("click",function ()
	{
		oShadow.hide();;
		oPopup.hide();;
	});
	$(".cancel").on("click",function(){
		oShadow.hide();;
		oPopup.hide();;
	});
	oStart.on("click",function(){
		KISSY.io({
			url: "/?a=tsm_st&m=Shopmodule",
			data:{"top_sign":top_sign},
			success: function(data, textStatus) {
				if(data.status==true){
					game_start();
				}else{
					alert('游戏开始失败！请确认您是在店铺中玩游戏，我们不接待来路不明的客户！');
				}
			},
			error: function(){
				alert('error');
			},
			//发送请求类型是jsonp
			dataType:"jsonp"
		});
	});
	
	function game_start()
	{
		iTimerBullet=null;
		aBullet=[];
		MAX_SPEED=5;
		MIN_SPEED=2;
		SCREEN_TIME=3;
		COUNT_BULLET=10;
		iLevel=1;
		iScore=0;
		i=0;
		aBullet.length=0;
	
		oMan.show();
		oImgLog.hide();
		$(".pos_1").hide();
		$(".pos_2").hide();
		$(".bullet").remove();
		//移动红快
		var lx;
		var ping=[];
		var issub=false;
		var bdwd = $(".mainContent").width();
		$(".bg").on("mousemove",function (e)
		{
			var l=e.pageX-280-(bdwd>=990?(bdwd-990)/2:0)-17;
			var t=e.pageY-20;
			if(l<0)
			{
				l=0;
			}
			else if(l>=oBg.width-oMan.width)
			{
				l=oBg.width-oMan.width;
			}
			
			if(t<0)
			{
				t=0;
			}
			else if(t>=oBg.height-oMan.height)
			{
				t=oBg.height-oMan.height;
			}
			if(lx>l){
				oMan.css("background-position",'34px');
			}else{
				oMan.css("background-position",'0');
			}
			lx=l;
			if(ping.length<100&&!issub){
				ping.push("x"+l+"y"+t);
			}else{
				ping.length = 0;
				issub=true;
			}
			oMan.css("left",l+'px');
			oMan.css("top",t+'px');
		});
		
		//子弹
		var startTime=(new Date()).getTime();
		var startTimeAll=(new Date()).getTime();
		var ts=0;
		iTimerBullet=setInterval(function (){
		// alert(aBullet.length);
			for(i=0;i<aBullet.length;i++)
			{
				
				  var xx = aBullet[i].x=aBullet[i].x+aBullet[i].speedX;
				  var yy = aBullet[i].y=aBullet[i].y+aBullet[i].speedY;
				  
				  if(KISSY.UA.ie<9){
					xx = aBullet[i].x=aBullet[i].x+aBullet[i].speedX+7;
				    yy = aBullet[i].y=aBullet[i].y+aBullet[i].speedY+7;
				  }
				// ********
				// aBullet[i].obj.css({"top":yy+'px',"left":xx+'px'});
				aBullet[i].obj.css("left",xx+'px');
				aBullet[i].obj.css("top",yy+'px');
				
				if(aBullet[i].x<0 || aBullet[i].x>380 || aBullet[i].y<0 || aBullet[i].y>320)
				{
					removeBullet(aBullet[i]);
					createBullet();
					i--;
				}
				
				if(cd(aBullet[i].obj, oMan))
				{
					clearInterval(iTimerBullet);
					$(".bg").detach("mousemove");
					// document.onmousemove=null;
					oGameOver.show();
					
					if(KISSY.UA.ie<9){
						$(".js-ieerr").remove();
						$("<span class=\"js-ieerr\" style=\"color:red\">您正在使用低版本的ie浏览器，请更换非ie内核的浏览器或升级到更高版本，这样游戏效果会更流畅！</span>").insertAfter(".game_over");
					}
					if(iScore>=3){
						var ti = new Date().getTime();
						var top_parameters = $(".top_parameters").val();
						var sign = R(sid+"|"+iScore+"|"+iLevel+"8o79a"+ti);
						KISSY.io({
							url: "/?a=tsm_ed&m=Shopmodule",	
							data:{"score":iScore,"level":iLevel,"shop_id":sid,"ts":ti,"top_sign":top_sign,"top_parameters":top_parameters,"sign":sign},
							success: function(data, textStatus) {
								if(data.status==true){
									$(".scoreid").val(data.score_id);
									lastscoreid = data.score_id;
									lotts = data.lotts;
									lastrange = data.range;
									var ctxt = "　　恭喜您获得了本轮“第 "+data.range+" 名”的好成绩！您获得了"+data.lotts+"次抽奖机会，您可以选择：";
									$(".ctxt").html(ctxt);
									$(".pos_1").show();
								}else{
									alert("抱歉，签名验证错误。");
								}
							},
							error: function(){
								alert('error');
							},
							//发送请求类型是jsonp
							dataType:"jsonp"
						});
					}else{
						var ctxt = "<br />　　啊哦，鼠标是不是跑偏了？没关系，再来一次！";
						$(".ctxt").html(ctxt);
						$(".pos_2").show();
					}
				}
			}
			
			var t=(new Date()).getTime()-startTimeAll;
			iScore=parseInt(t/1000);
			oScore.html('<li>难度：'+iLevel+'</li><li>坚持：'+iScore+'秒</li>');
			
			var t=(new Date()).getTime()-startTime;
			var scale=100*(1-t/(SCREEN_TIME*1000));
			
			if(scale<=0)
			{
				// 进度条
				// oProgressSpan.css("width",0+'%');
				startTime=(new Date()).getTime();
				createBullet();
				COUNT_BULLET++;
				MAX_SPEED+=0.5;
				iLevel++;
			}
			else
			{
				// oProgressSpan.css("width",scale+'%');
			}
			if(ts%990==0){
				KISSY.io({
				url: "/?a=tsm&m=Shopmodule",
				data:{"ping":ping},
				success: function(data, textStatus) {
					if(data.status==true){
					// $(".wins").text(data.ping);
					ping.length=0;
					issub=false;
					}else{
						clearInterval(iTimerBullet);
						$(".bg").detach("mousemove");
						// document.onmousemove=null;
						$(".game_restart").show();
					}
				},
				error: function(){
					alert('error');
				},
				//发送请求类型是jsonp
				dataType:"jsonp"
				});
			}
			ts+=30;
			//document.title=100*(1-t/(SCREEN_TIME*1000));
		}, 30);
		
		function createBullet()
		{
		
			var x,y,speedX,speedY;
			
			do
			{
				var left=rnd(0,2);
				var top=rnd(0,2);
			}while(!(left==1 && top!=1 || left!=1 && top==1));
			
			if(0==left)
			{
				x=0;
				speedX=rnd(MIN_SPEED, MAX_SPEED);
			}
			else if(1==left)
			{
				x=rnd(0, 320);
				speedX=rnd(-MAX_SPEED, MAX_SPEED);
			}
			else
			{
				x=380;
				speedX=-rnd(MIN_SPEED, MAX_SPEED);
			}
			
			if(0==top)
			{
				y=0;
				speedY=rnd(MIN_SPEED, MAX_SPEED);
			}
			else if(1==top)
			{
				y=rnd(0, 380);
				speedY=rnd(-MAX_SPEED, MAX_SPEED);
			}
			else
			{
				y=320;
				speedY=-rnd(MIN_SPEED, MAX_SPEED);
			}
			
			var oDiv=$('<div></div>');
			oDiv.addClass('bullet');
			// oDiv.css( {"top": y+'px', "left": x+'px'});
			oDiv.css("left",x+'px');
			oDiv.css("top",y+'px');
			
			oDiv.appendTo(oBg);
			aBullet.push({obj: oDiv, x: x, y: y, speedX: speedX, speedY: speedY});
		}
		
		function removeBullet(oBullet)
		{
			var aResult=[];
			for(i=0;i<aBullet.length;i++)
			{
				if(aBullet[i]!=oBullet)
				{
					aResult.push(aBullet[i]);
				}
			}
			oBullet.obj.remove();
			// oBg.removeChild(oBullet.obj);
			
			aBullet=aResult;
		}
		
		for(i=0;i<COUNT_BULLET;i++)
		{
			createBullet();
		}
		
		function cd(obj1, obj2)
		{
			var l1=obj1.offset().left;
			var r1=obj1.offset().left+5;
			var t1=obj1.offset().top;
			var b1=obj1.offset().top+5 ;
			
			var l2=obj2.offset().left;
			var r2=obj2.offset().left+34;
			var t2=obj2.offset().top;
			var b2=obj2.offset().top+40 ;
			
			if(r1<l2 || l1>r2 || b1<t2 || t1>b2)
			{
				return false;
			}
			else
			{
				return true;
			}
		}
		oStart.hide();;
	}

function auth()
{
	var oScore=document.getElementsByName('cmt_score')[0];
	var oLevel=document.getElementsByName('cmt_level')[0];
	var oName=document.getElementsByName('cmt_name')[0];
	
	if(!oName.value)
	{
		alert('请填写姓名');
		return false;
	}
}

var anim = new KISSY.LayerAnim(
    {

        node: '.wins ul',
        form: {
            scrollTop: 0
        },
        to: {
            scrollTop: 100
        },
		duration: 5,
		yoyo:true,
		repeatDelay:5,
        repeat: -1
    });
anim.run();
// });